﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using System.Drawing;
using System.Diagnostics;

namespace ChatTool
{
    /// <summary>
    /// 处理传送文件的接收
    /// </summary>
    public class FileReceive
    {
        private UserClient userClient;
        private ToolStrip ts = new ToolStrip();
        private ToolStripProgressBar tspb = new ToolStripProgressBar();
        private ToolStripButton tsb = new ToolStripButton();
        private FormChatToOne formChatToOne;
        private string fileName;
        private int fileLength;
        private FileStream fs;

        public FileReceive(UserClient userClient, FormChatToOne formChatToOne)
        {
            this.userClient = userClient;
            this.formChatToOne = formChatToOne;

            tsb.Text = "接收";
            tspb.ToolTipText = fileName;
            tsb.Click += new EventHandler(tsb_Click);
            ts.GripStyle = ToolStripGripStyle.Hidden;
            ts.BackColor = System.Drawing.Color.Transparent;
            ts.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { tspb, tsb });     
        }

        private void tsb_Click(object sender, EventArgs e)
        {
            ToolStripButton tsb = sender as ToolStripButton;
            string text = tsb.Text;
            if (text == "接收")
            {
                FolderBrowserDialog dialog = new FolderBrowserDialog();
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    string savePath = dialog.SelectedPath + "\\" + fileName;//文件保存路径
                    try
                    {
                        fs = File.Create(savePath);
                    }
                    catch (Exception ee)
                    {
                        MessageBox.Show("选择文件保存路径异常: " + ee.Message);
                        return;
                    }
                   
                }
                else
                    return;
                tsb.Text = "中止";
                Thread receiveThread = new Thread(ReceiveFileData);
                receiveThread.IsBackground = true;
                receiveThread.Start();
                
                NetManager.SendStringMsgToServer(userClient, "Agree");
            }
            else
            {
                userClient.Close();
                fs.Close();
                this.formChatToOne.AddOrDeleteToolStripToPanel("Delete", ts);
            }
        }
        private void ReceiveFileData()
        {
            try
            {
                int readLength = 0;
                int receivedLength = 0;
                Stopwatch watch = new Stopwatch();
                watch.Start();
                while (receivedLength < fileLength)
                {
                    readLength = userClient.Br.ReadInt32();
                    byte[] bs = userClient.Br.ReadBytes(readLength);
                    fs.Write(bs, 0, readLength);//写入文件
                    receivedLength += readLength;
                    this.HandleSysncContrl(this.tspb, "UpdateProgressRate", readLength.ToString());
                }
                watch.Stop();
                long useTimeMS = watch.ElapsedMilliseconds;
                long useTimeS = useTimeMS / 1000;
                long useTimeMin = useTimeS / 60;
                string useTimeStr = "";
                if (useTimeMin >= 1)
                    useTimeStr = useTimeMin + "分";
                else if(useTimeS>=1)
                    useTimeStr = useTimeS + "秒";
                else
                    useTimeStr = useTimeMS + "毫秒";
                double speedKB = (1.0 * this.fileLength / 1024) / (useTimeMS / 1000);//   KB/S表示
                double speedMB = 1.0 * speedKB / 1024;//  MB/S表示
                string speedStr = "";
                if (speedMB >= 1.0)
                    speedStr = string.Format("{0:0.##}MB/S", speedMB);
                else
                    speedStr = (int)speedKB + "";
                string waringInfo = "文件[" + this.fileName + "]传送完毕,用时:" + useTimeStr + ",平均传送速度:" + speedStr;
                this.formChatToOne.AddWaringInfoToRtContent(waringInfo);
            }
            catch (Exception ee)
            {
                MessageBox.Show("文件接收时异常：" + ee.Message);
            }
            finally
            {
                userClient.Close();
                fs.Close();
                this.formChatToOne.AddOrDeleteToolStripToPanel("Delete", ts);
            }
        }
        private delegate void HandleSysncControlDelegate(Object control, string cmd, string data);
        /// <summary>
        /// 异步操作控件
        /// </summary>
        private void HandleSysncContrl(Object control, string cmd, string data)
        {
            HandleSysncControlDelegate d = ExecHandleSysncContrl;
            this.formChatToOne.Invoke(d, control, cmd, data);
        }
        private void ExecHandleSysncContrl(Object control, string cmd, string data)
        {
            if (control is ToolStripProgressBar)
            {
                ToolStripProgressBar toolBar = control as ToolStripProgressBar;
                if (cmd == "UpdateProgressRate")
                    toolBar.Value += Int32.Parse(data);
            }
        }
        /// <summary>
        /// 确认是否接收文件
        /// </summary>
        public void Receive()
        {
            this.fileName = userClient.Br.ReadString();//读取文件名
            this.fileLength = Int32.Parse(userClient.Br.ReadString());//读取文件长度

            this.formChatToOne.AddOrDeleteToolStripToPanel("Add", ts);
            this.tspb.Value = 0;
            this.tspb.Maximum = this.fileLength;
            this.tspb.AutoSize = false;
            this.tspb.Size = new System.Drawing.Size(100, 15);
            string fileSize = Tool.GetFileSizeFromByteCount(this.fileLength);
            tspb.ToolTipText = Path.GetFileName(fileName) + " [文件大小: " + fileSize + "]";

            string rtf = Tool.GetRtfString("对方发来文件[" + fileName + "][" + fileSize + "],点击右边的按钮处理.", Tool.Font, Color.Brown);
            this.formChatToOne.AddRtfByClipboard(rtf);
        }

    }
}
